JavaScript Variable Declarations

Visualizing `var`, `let`, `const`, and the new `using` declarations.

`var`, `let`, `const`

The three primary ways to declare variables, each with different scoping and mutability rules. `var` is function-scoped, while `let` and `const` are block-scoped. `const` also prevents re-assignment.

const name = "Alice"; // Fixed value
let count = 0;      // Can be changed
var legacy = 1;     // Old, but works

`const` userName: Sarah

`let` userAge: 25

`var` highscore: 100


Block Scoping (`let` vs `var`)

`let` and `const` are confined to the block (`{ ... }`) they are declared in. `var` is hoisted and has function scope, leading to common bugs. `let` and `const` prevent this by being more predictable.

if (true) {
  var varVariable = "accessible outside";
  let letVariable = "inaccessible outside";
}
console.log(varVariable); // Works!
console.log(letVariable); // Error!

Inside a code block:

`let` status:

`var` status:


`using` & `await using` (ES2023+)

The `using` declaration provides a clean syntax for managing resources that need to be explicitly cleaned up (e.g., a file handle or a database connection). It works with objects that implement the `[Symbol.dispose]` method. `await using` is used for asynchronous resources.

// Resource class
class MyResource {
  [Symbol.dispose]() {
    console.log('Resource cleaned up.');
  }
}
{
  using myResource = new MyResource();
  // ... do work with myResource
} // Resource is automatically disposed here

Resource: Not created

Lifecycle Log: